package modulos;

import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import plantable.AttributiveCellRenderer;
import plantable.CellSpan;
import plantable.MultiSpanCellTable;
import plantable.TableModelAttributiveCell;
import auxiliary.Constants;
import auxiliary.Database;
import auxiliary.GercoPlaneacion;
import auxiliary.Planner;

public class PanelPlan extends JPanel implements ActionListener,
		PropertyChangeListener, MouseListener {

	private static final long serialVersionUID = 1L;
	JProgressBar pbar;
	int counter;
	JTable jt;
	MultiSpanCellTable mt;
	TableModelPlan ftm;
	PanelPlan panel;
	Border raisedbevel;
	TableModelAttributiveCell ml;
	CellSpan cellAtt;
	ArrayList<String> years;
	JInternalFrame gridFrame;
	JPanel buttonPanel, glassPanel, gridPanel;
	String[] months, days;
	int[] monthDays;
	int currentMonth, currentYear;
	JPanel cards, panelInicial, panelErrorListaNoCreada, panelErrorActualizacionPendiente, labelPanel;
	JLabel label;
	JComboBox yearCombo, daysCombo, monthsCombo;
	Task task;
	ProgressMonitor progdialog;
	ImageIcon imageicon, pdficon, planicon, actualizaricon, starchiicon, starryicon;
	JLabel imagelabel,starchilabel;
	JButton mostrarButton, actualizarButton, pdfButton;
	Database db;
	Planner plan;
	String month, year;
	int day,dayselected;
	JScrollPane jsp;
	JViewport jv;
	boolean show;
	boolean changestatus;
	boolean confirmado;
	JFrame parent;
	// Lock lock;

	
	class Task extends SwingWorker<Void, Void> {
		/*
		 * Main task. Executed in background thread.
		 */
		String modo;
		
		Task(String modo) {
			this.modo = modo;
		}
		
		public synchronized Void doInBackground() {
			@SuppressWarnings("unused")
			Random random = new Random();
			int progress = 0;
			// Initialize progress property.
			setProgress(0);
			plan = new Planner(day, month, year,modo,dayselected);
			plan.start();
			while (progress < 108) {
				// Sleep for up to one second.
				try {
					// plan.start();
					////System.out.println("entro a swingworker");
					Thread.sleep(/* random.nextInt(1000) */1000);
				} catch (InterruptedException ignore) {
				}
				// Make random progress.

				// progress += random.nextInt(10);
				progress = plan.getCurrTime();
				setProgress(Math.min(progress, 110));
				////System.out.println("cambio el progress");
			}
			// progdialog.dispose();
			return null;
		}

		/*
		 * Executed in event dispatching thread
		 */
		@Override
		public void done() {
			progdialog.dispose();
			setProgress(0);
			Toolkit.getDefaultToolkit().beep();
			// startButton.setEnabled(true);
			setCursor(null); // turn off the wait cursor
			// taskOutput.append("Done!\n");
		}
	}

	class ProgressMonitor extends JDialog {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		Container contentPane;
		Timer timer;

		public ProgressMonitor(JFrame parent) {
			super(parent, "Progreso");
			counter = 0;

			pbar = new JProgressBar(0, 100);

			contentPane = getContentPane();

			contentPane.add(BorderLayout.CENTER, pbar);
			contentPane.add(BorderLayout.NORTH, new JLabel("Progreso de tarea..."));
			this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
			// dlg.setSize(300, 75);

			// Fire a timer every once in a while to update the progress.

			// pack();
			// setVisible(true);

		}
	}

	public PanelPlan(GercoPlaneacion parent) {
		//super(parent);
		show = false;
		this.parent = parent;
		db = new Database();
		
		
		// lock = new Lock();

		currentMonth = Calendar.getInstance().get(Calendar.MONTH);
		currentYear = Calendar.getInstance().get(Calendar.YEAR);
		months = new String[] { "Ene", "Feb", "Mar", "Abr", "May", "Jun",
				"Jul", "Ago", "Sep", "Oct", "Nov", "Dic" };
		years = new ArrayList<String>();
		monthDays = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		days = new String[] { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado" };

		progdialog = new ProgressMonitor(Constants.getParentFrame(this));
		// progdialog.setVisible(false);

		URL imgURL = ClassLoader.getSystemResource("images/back.png");
		Image image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		imageicon = new ImageIcon(image);
		imagelabel = new JLabel(imageicon);
		
		imgURL = ClassLoader.getSystemResource("images/pdf.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);
		
		pdficon = new ImageIcon(image);
		
		Image img = pdficon.getImage();  
		Image newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		pdficon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/update.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		actualizaricon = new ImageIcon(image);
		
		img = actualizaricon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		actualizaricon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/plan.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		planicon = new ImageIcon(image);
		
		img = planicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		planicon = new ImageIcon(newimg);
		
		imgURL = ClassLoader.getSystemResource("images/starchi.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		starchiicon = new ImageIcon(image);
		
		img = starchiicon.getImage();  
		newimg = img.getScaledInstance(20, 20,  java.awt.Image.SCALE_SMOOTH);  
		starchiicon = new ImageIcon(newimg);
		starchilabel = new JLabel(starchiicon);
		starchilabel.setBorder(new EmptyBorder(3,15,3,3));
		
		imgURL = ClassLoader.getSystemResource("images/starry.png");
		image = Toolkit.getDefaultToolkit().getImage(imgURL);

		starryicon = new ImageIcon(image);
		
		img = starryicon.getImage();  
		newimg = img.getScaledInstance(40, 40,  java.awt.Image.SCALE_SMOOTH);  
		starryicon = new ImageIcon(newimg);

		for (int i = 0; i < 20; i++) {
			years.add(Integer.toString(2011 + i));
		}

		
		yearCombo = new JComboBox(Constants.singleArrayListToString(years));
		monthsCombo = new JComboBox(Constants
				.getStartWeek(String.valueOf((Integer
						.valueOf((String) yearCombo.getSelectedItem())))));
		
		//String selected = (String) monthsCombo.getSelectedItem();
		//String array[] = selected.split("/");	
		//int startday = Integer.valueOf(array[0]);
		
		/*days = new String[] { String.valueOf(startday), String.valueOf(startday+1), 
				String.valueOf(startday+2), String.valueOf(startday+3), String.valueOf(startday+4), 
				String.valueOf(startday+5), String.valueOf(startday+5) };*/
		
		
		
		daysCombo = new JComboBox(days);
		daysCombo.setActionCommand("daysComboChanged");
		daysCombo.setEnabled(false);
		
		monthsCombo.setActionCommand("monthsComboChanged");
		
		yearCombo.addActionListener(this);
		daysCombo.addActionListener(this);
		monthsCombo.addActionListener(this);

		panel = this;

		mostrarButton = new JButton("Mostrar");
		mostrarButton.setActionCommand(Constants.PLAN_MOSTRAR);
		mostrarButton.addActionListener(this);

		buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

		glassPanel = new JPanel()  
		{  
		   /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

		public void paintComponent(Graphics g)  
		   {  
		      //Set the color to with red with a 50% alpha  
		      g.setColor(new Color(0, 0, 0, 0.5f));  
		   
		      //Fill a rectangle with the 50% red color  
		      g.fillRect(0, 0, this.getWidth(), this.getHeight());  
		   }  
		};  
		
		////System.out.println("toplevelancestor" + parent.getName());
		glassPanel.setOpaque(false);  
  
		
		
		//glassPanel.setVisible(true); 
		
		gridPanel = new JPanel(new BorderLayout());
		gridFrame = new JInternalFrame();
		//gridFrame.setBorder(null);
		gridFrame.setGlassPane(glassPanel);
		gridPanel.add(gridFrame);
		
		JPanel topPanel = new JPanel(new BorderLayout());

		// yearCombo = new JComboBox(Constants.singleArrayListToString(years));
		// monthsCombo = new JComboBox(months);
		// daysCombo = new JComboBox(Constants.singleArrayListToString(days
		// .get(currentMonth)));

		JPanel leftPanel = new JPanel(new BorderLayout());
		JPanel datePanel = new JPanel(new BorderLayout());
		JPanel mostrarPanel = new JPanel(new BorderLayout());

		leftPanel.add(datePanel, BorderLayout.CENTER);
		leftPanel.add(mostrarPanel, BorderLayout.EAST);

		topPanel.add(leftPanel, BorderLayout.EAST);

		datePanel.add(daysCombo, BorderLayout.WEST);
		datePanel.add(monthsCombo, BorderLayout.CENTER);
		datePanel.add(yearCombo, BorderLayout.EAST);

		leftPanel.add(mostrarButton, BorderLayout.EAST);

		cards = new JPanel(new CardLayout());
		
		panelInicial = new JPanel(new BorderLayout());
		panelErrorListaNoCreada = new JPanel(new BorderLayout());
		panelErrorActualizacionPendiente = new JPanel(new BorderLayout());

		String textoPanelInicial = "<html><B>Por favor seleccione una combinacion Semana/A&ntilde;o "
				+ "para ver plan para esa fecha</B>";
		String textoErrorListaNoCreada = "<html><FONT COLOR=RED><B>No se ha creado lista de produccion para la fecha seleccionada</B></FONT>";
		String textoErrorActualizacionPendiente = "<html><FONT COLOR=RED><B>Existe una actualizacion pendiente </B></FONT>";
		
		JLabel labelPanelInicial = new JLabel(textoPanelInicial, JLabel.CENTER);
		JLabel labelErrorListaNoCreada = new JLabel(textoErrorListaNoCreada, JLabel.CENTER);
		JLabel labelErrorActualizacionPendiente = new JLabel(textoErrorActualizacionPendiente, JLabel.CENTER);

		panelInicial.add(labelPanelInicial, BorderLayout.CENTER);
	
		JPanel imagePanel = new JPanel(new BorderLayout());
		imagePanel.add(imagelabel, BorderLayout.EAST);
		
		/*starchilabel = new JLabel(starchiicon);
		starchilabel.setBorder(new EmptyBorder(3,15,3,3));
		starchilabel.addMouseListener(this);
		starchilabel.setName("starchi");
		imagePanel.add(starchilabel, BorderLayout.WEST);*/
		
		panelInicial.add(imagePanel, BorderLayout.SOUTH);
		panelErrorListaNoCreada.add(labelErrorListaNoCreada, BorderLayout.CENTER);
		panelErrorActualizacionPendiente.add(labelErrorActualizacionPendiente, BorderLayout.CENTER);
		
		JPanel imagePanel2 = new JPanel(new BorderLayout());
		imagePanel2.add(new JLabel(imageicon), BorderLayout.EAST);
		
		/*starchilabel = new JLabel(starchiicon);
		starchilabel.setBorder(new EmptyBorder(3,15,3,3));
		imagePanel2.add(starchilabel, BorderLayout.WEST);*/
		
		panelErrorListaNoCreada.add(imagePanel2, BorderLayout.SOUTH);
		
		actualizarButton = new JButton("Actualizar",actualizaricon);
		actualizarButton.setActionCommand(Constants.PLAN_ACTUALIZAR);
		actualizarButton.addActionListener(this);
		
		JPanel errorActualizarButtonPanel = new JPanel();
		errorActualizarButtonPanel.setLayout(new BoxLayout(errorActualizarButtonPanel, BoxLayout.X_AXIS));
		
		errorActualizarButtonPanel.add(Box.createHorizontalGlue());
		
		errorActualizarButtonPanel.add(actualizarButton, BorderLayout.CENTER);
		
		errorActualizarButtonPanel.add(Box.createHorizontalGlue());
		errorActualizarButtonPanel.add(imagelabel, BorderLayout.EAST);
		panelErrorActualizacionPendiente.add(errorActualizarButtonPanel, BorderLayout.SOUTH);

		cards.add(panelInicial, Constants.PlanLabel.PANEL_INICIAL.toString());
		cards.add(panelErrorListaNoCreada, Constants.PlanLabel.PANEL_ERROR_LISTA_NO_CREADA.toString());
		cards.add(panelErrorActualizacionPendiente, Constants.PlanLabel.PANEL_ERROR_ACTUALIZACION_PENDIENTE.toString());
		cards.add(gridPanel, Constants.PlanLabel.GRID_PANEL.toString());

		this.setLayout(new BorderLayout());
		this.add(topPanel, BorderLayout.NORTH);
		this.add(cards, BorderLayout.CENTER);

	}

	public void createPlan(String day, String month, String year, boolean mostraroactualizar) {
		// plan = new Planner(day, month, year);
		// plan.start();

		if(mostraroactualizar) {
			plan = new Planner(Integer.valueOf(day), month, year, "", dayselected);
			plan.start();

		while (plan.done == false) {
				try {
					// pbar.
					Thread.sleep(10);
					// task.firePropertyChange(day, month, year);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		show = plan.exists;
		
		}
		else {
			show = true;
		}
		
		/*while (plan.done == false) {
			try {
				// pbar.
				Thread.sleep(1000);
				// task.firePropertyChange(day, month, year);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		
		
		

		plan.printTable(dayselected+1);
		
		ml = plan.ml;
		cellAtt = plan.cellAtt;
		
		

		/***
		 * adding table to gridpanel and showing it
		 */

		int dayselected = daysCombo.getSelectedIndex();
		int lastdia = db.retrieveLastDiaConfirmado(Integer.valueOf(day),month,year);
		
		boolean previouscheck = true;
		
		buttonPanel = new JPanel();
		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));

		actualizarButton = new JButton("Actualizar",actualizaricon);
		actualizarButton.setActionCommand(Constants.PLAN_ACTUALIZAR);
		actualizarButton.addActionListener(this);

		pdfButton = new JButton("Generar PDF",pdficon);
		pdfButton.setActionCommand(Constants.PLAN_GENERAR_PDF);
		pdfButton.addActionListener(this);
		
		if(dayselected!=0) {
			
			if(lastdia==dayselected) {
				actualizarButton.setEnabled(true);
			}
			else {
				actualizarButton.setEnabled(false);
			}
		}
		else {
			
			String array[] = ((String) monthsCombo.getSelectedItem()).split("/");
			
			if(lastdia==dayselected) {
				actualizarButton.setEnabled(true);
			}
			else if(lastdia>=dayselected+1) {
				actualizarButton.setEnabled(false);
			}
			/*else {
				int monthindex = monthsCombo.getSelectedIndex();
				if(monthindex == 0 && (yearCombo.getSelectedIndex() == 0)) {
					actualizarButton.setEnabled(true);
				}
				else {
					if(monthindex == 0) {
						int previousyear = (Integer.valueOf((String) yearCombo.getItemAt(yearCombo.getSelectedIndex()-1)));
						String[] previousweeks = Constants.getStartWeek(String
								.valueOf(previousyear));
						
						String newarray[] = previousweeks[previousweeks.length-1].split("/");
						if(newarray[0].equals(array[0]) 
								&& newarray[1].equals(array[1])
								&& newarray[2].equals(array[2])) {
							newarray = previousweeks[previousweeks.length-2].split("/");
						}
						array = newarray.clone();
					}
					else {
						array = ((String) monthsCombo.getItemAt(monthsCombo.getSelectedIndex()-1)).split("/");
					}
					
					int lastday = Integer.valueOf(array[0]);
					String lastmonth = array[1];
					String lastyear = array[2];
					
					int confirmados = db.countLastWeekConfirmados(lastday,lastmonth,lastyear);
					
					if(confirmados == 6) {
						actualizarButton.setEnabled(true);
					} else{
						actualizarButton.setEnabled(false);
						previouscheck = false;
					}
				}
			}*/
		}
		
		if(show && previouscheck) {
			
			
	
			
			gridPanel = new JPanel(new BorderLayout());
			
			gridFrame = new JInternalFrame();
			//gridFrame.setBorder(null);
			gridFrame.setClosable(false);
			//gridFrame.setFrameIcon(null); 
			gridFrame.setMaximizable(false);
		
		
		
		//for(MouseListener listener : ((javax.swing.plaf.basic.BasicInternalFrameUI) gridFrame.getUI()).getNorthPane().getMouseListeners()){
		//	((javax.swing.plaf.basic.BasicInternalFrameUI) gridFrame.getUI()).getNorthPane().removeMouseListener(listener);
		//}
		
		javax.swing.plaf.InternalFrameUI ifu= gridFrame.getUI();
		((javax.swing.plaf.basic.BasicInternalFrameUI)ifu).setNorthPane(null);
		
		try {
			gridFrame.setSelected(true);
		} catch (PropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		gridFrame.setGlassPane(glassPanel);
		gridFrame.setVisible(true);
		//gridFrame.setEnabled(false);

		
		

		TableColumnModel cm = new DefaultTableColumnModel() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			boolean first = true;

			public void addColumn(TableColumn tc) {
				if (first) {
					first = false;
					return;
				}
				tc.setMinWidth(65);
				super.addColumn(tc);
			}
		};

		TableColumnModel rowHeaderModel = new DefaultTableColumnModel() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			boolean first = true;

			public void addColumn(TableColumn tc) {
				if (first) {
					tc.setMinWidth(200);
					tc.setMaxWidth(tc.getPreferredWidth());
					super.addColumn(tc);
					first = false;
				}
			}
		};

		mt = new MultiSpanCellTable(ml, cm);
		JTable headerColumn = new JTable(ml, rowHeaderModel);
		headerColumn.setRowHeight(2);
		mt.setRowHeight(mt.getRowHeight() * 2);
		mt.createDefaultColumnsFromModel();
		headerColumn.createDefaultColumnsFromModel();

		mt.setSelectionModel(headerColumn.getSelectionModel());
		mt.setDefaultRenderer(Object.class, new AttributiveCellRenderer());

		headerColumn.setDefaultRenderer(Object.class,
				new AttributiveCellRenderer());
		headerColumn.setEnabled(false);
		headerColumn.setRowHeight(60);
		headerColumn.getTableHeader().setReorderingAllowed(false);

		mt.setEnabled(false);
		mt.setRowHeight(60);
		mt.getTableHeader().setReorderingAllowed(false);
		mt.getTableHeader().setResizingAllowed(false);

		jv = new JViewport();
		jv.setView(headerColumn);
		jv.setPreferredSize(headerColumn.getMaximumSize());

		mt.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

		jsp = new JScrollPane(mt);
		jsp.setRowHeader(jv);
		jsp.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, headerColumn
				.getTableHeader());
		jsp.setPreferredSize(new Dimension(900, 450));
		
		

		//buttonPanel.add(starchilabel);
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(actualizarButton, BorderLayout.EAST);
		buttonPanel.add(pdfButton, BorderLayout.EAST);
		//buttonPanel.add(Box.createHorizontalGlue());
		
		buttonPanel.add(Box.createHorizontalGlue());
		buttonPanel.add(imagelabel, BorderLayout.EAST);
		
		gridFrame.add(jsp,BorderLayout.CENTER);
		gridPanel.add(gridFrame, BorderLayout.CENTER);
		gridPanel.add(buttonPanel, BorderLayout.SOUTH);

		cards.remove(3);
		}
		else {
			
			buttonPanel = new JPanel();
			buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
	
			actualizarButton = new JButton("Crear Plan",planicon);
			actualizarButton.setActionCommand(Constants.PLAN_ACTUALIZAR);
			actualizarButton.addActionListener(this);
			if(!previouscheck)
				actualizarButton.setEnabled(false);
			
			buttonPanel.add(Box.createHorizontalGlue());
			buttonPanel.add(actualizarButton, BorderLayout.EAST);
			buttonPanel.add(Box.createHorizontalGlue());
			
			JPanel imagePanel = new JPanel(new BorderLayout());
			imagePanel.add(imagelabel, BorderLayout.EAST);
			//imagePanel.add(starchilabel, BorderLayout.WEST);
			
			
			gridPanel = new JPanel(new BorderLayout());
			
			JPanel errorPanel = new JPanel(new BorderLayout());
			
			String labelText = "";
			//if(previouscheck)
				labelText = "<html><FONT COLOR=RED><B>No se ha creado Plan haga click en Crear para iniciar planeamiento </B></FONT>";
			//else 
			//	labelText = "<html><FONT COLOR=RED><B>Se deben confirmar dias previos antes de crear plan de semana siguiente </B></FONT>";
				
			JLabel textLabel = new JLabel(labelText, JLabel.CENTER);
		
			errorPanel.add(textLabel,BorderLayout.CENTER);
			errorPanel.add(buttonPanel,BorderLayout.SOUTH);
			
			gridPanel.add(errorPanel, BorderLayout.CENTER);
			gridPanel.add(imagePanel, BorderLayout.SOUTH);
			
		}
		cards.add(gridPanel, Constants.PlanLabel.GRID_PANEL.toString());
	}
	
	public void actionPerformed(ActionEvent e) {

		String command = e.getActionCommand();

		String array[] = ((String) monthsCombo.getSelectedItem()).split("/");

		ArrayList<ArrayList<String>> listOfMensuales = db.retrieveMensuales(
				array[0], array[1], array[2]);

		dayselected = daysCombo.getSelectedIndex();
		
		int currentDia = Integer.valueOf(array[0])+Integer.valueOf(dayselected);
		//int actualizarDia = db.actionToPerform(Integer.valueOf(array[0]), currentDia , array[1], array[2], "actualizar");
		
		////System.out.println("command=" + command);
		if (command == Constants.PLAN_MOSTRAR) {
			
			
			((GercoPlaneacion) parent).setMonthSelection(monthsCombo.getSelectedIndex());
			((GercoPlaneacion) parent).setYearSelection(yearCombo.getSelectedIndex());
			((GercoPlaneacion) parent).setDaySelection(daysCombo.getSelectedIndex());
			
			
			if(mostrarButton!=null) {
				mostrarButton.setEnabled(true);
			}
			if(monthsCombo!=null) {
				monthsCombo.setEnabled(true);
			}
			if(yearCombo!=null) {
				yearCombo.setEnabled(true);
			}
			if(daysCombo!=null) {
				daysCombo.setEnabled(true);
			}
			
			this.repaint();
			
			CardLayout cl = (CardLayout) (cards.getLayout());
			if (listOfMensuales.size() > 0) {

				
				
				day = Integer.valueOf(array[0]);
				month = array[1];
				year = array[2];
				
				
				
				/********************
				 * 
				 * se muestra el plan si este ya existe en la base de datos
				 * o se da la opcion de crearlo si no existe
				 * 
				 */
				
				//if(day+dayselected <=)

				/*setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
				task = new Task("mostrar");
				task.addPropertyChangeListener(this);
				task.execute();
				progdialog
						.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
				progdialog
						.setLocationRelativeTo(Constants.getParentFrame(this));
				progdialog.pack();
				progdialog.setVisible(true);

				daysCombo.setSelectedIndex(0);*/
				daysCombo.setEnabled(true);
				
				// this.removeAll();
				createPlan(array[0], array[1], array[2],true);
				
				
				
				//jsp.setHorizontalScrollBarPolicy(counter);

				cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
			} else if(listOfMensuales.size() == 0){
				
				daysCombo.setEnabled(false);
				cl.show(cards, Constants.PlanLabel.PANEL_ERROR_LISTA_NO_CREADA.toString());
			}
				
		} else if (command == Constants.PLAN_ACTUALIZAR) {

			CardLayout cl = (CardLayout) (cards.getLayout());
				/********************
				 * 
				 *  Se actualiza el plan desde cero
				 * 
				 * 
				 */
				/*if(actualizarDia == 0)
					dayselected = daysCombo.getSelectedIndex();
				else {
					dayselected = actualizarDia+1;
					db.performAction(actualizarDia, array[1], array[2], "actualizar");
				}*/
			
				dayselected = daysCombo.getSelectedIndex();
			
				day = Integer.valueOf(array[0]);
				month = array[1];
				year = array[2];
				
				//db.retrieveMensuales(

				setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
				task = new Task("actualizar");
				task.addPropertyChangeListener(this);
				task.execute();
				progdialog
						.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
				progdialog
						.setLocationRelativeTo(Constants.getParentFrame(this));
				progdialog.pack();
				progdialog.setVisible(true);

				// this.removeAll();
				createPlan(array[0], array[1], array[2],false);
				
				//daysCombo.setSelectedIndex(0);
				daysCombo.setEnabled(true);
				
				//jsp.setHorizontalScrollBarPolicy(counter);
				
				changestatus = true;

				cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
				
				mostrarButton.setEnabled(true);
				

		} else if (command == Constants.PLAN_GENERAR_PDF) {
			day = Integer.valueOf(array[0]);
			month = array[1];
			year = array[2];
			
			dayselected = daysCombo.getSelectedIndex();
			
			JFileChooser fc = new JFileChooser();
			int returnVal = fc.showDialog(this, "Guardar");
			
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				   File file = fc.getSelectedFile();
					plan.generatePDF(file,day+dayselected);
				} 
			
			
		} else if ("comboBoxChanged".equals(command)) {
			//System.out.println("User has selected an item from the combo box.");
			
			daysCombo.setEnabled(false);
			glassPanel.setVisible(true);
			
			if(jsp!=null) {
				jsp.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
				jsp.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

			}
			buttonPanel.setEnabled(false);
			if(actualizarButton!=null) {
				actualizarButton.setEnabled(false);
			}
			if(pdfButton!=null) {
				pdfButton.setEnabled(false);
			}
			
			monthsCombo = new JComboBox(Constants.getStartWeek(String
					.valueOf((Integer.valueOf((String) yearCombo
							.getSelectedItem())))));
			monthsCombo.setActionCommand("monthsComboChanged");
			monthsCombo.addActionListener(this);
			JPanel topPanel = new JPanel(new BorderLayout());

			// yearCombo = new
			// JComboBox(Constants.singleArrayListToString(years));
			// monthsCombo = new JComboBox(months);
			// daysCombo = new JComboBox(Constants.singleArrayListToString(days
			// .get(currentMonth)));

			JPanel leftPanel = new JPanel(new BorderLayout());
			JPanel datePanel = new JPanel(new BorderLayout());
			JPanel mostrarPanel = new JPanel(new BorderLayout());

			leftPanel.add(datePanel, BorderLayout.CENTER);
			leftPanel.add(mostrarPanel, BorderLayout.EAST);

			topPanel.add(leftPanel, BorderLayout.EAST);

			datePanel.add(daysCombo, BorderLayout.WEST);
			datePanel.add(monthsCombo, BorderLayout.CENTER);
			datePanel.add(yearCombo, BorderLayout.EAST);

			leftPanel.add(mostrarButton, BorderLayout.EAST);
			// topPanel

			this.removeAll();

			this.setLayout(new BorderLayout());
			this.add(topPanel, BorderLayout.NORTH);
			this.add(cards, BorderLayout.CENTER);
			// this.add(buttonPanel, BorderLayout.SOUTH);

			this.revalidate();
			this.repaint();
			this.setVisible(true);
		}
		else if("daysComboChanged".equals(command)) {
			
			CardLayout cl = (CardLayout) (cards.getLayout());
			
			day = Integer.valueOf(array[0]);
			month = array[1];
			year = array[2];
			
			dayselected = daysCombo.getSelectedIndex();
			
			plan.printTable(dayselected+1);

			// this.removeAll();
			createPlan(array[0], array[1], array[2], true);
			
			cl.show(cards, Constants.PlanLabel.GRID_PANEL.toString());
		}
		else if("monthsComboChanged".equals(command)) {
			//gridFrame.setEnabled(false);
			//mt.setEnabled(false);
			if(jsp!=null) {
				jsp.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
				jsp.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);
			}
			
			if(actualizarButton!=null) {
				actualizarButton.setEnabled(false);
				}
			if(pdfButton!=null) {
				pdfButton.setEnabled(false);
			}
			buttonPanel.setEnabled(false);

			glassPanel.setVisible(true);
			//CardLayout cl = (CardLayout) (cards.getLayout());
			
			//System.out.println("User has selected an item from the months combo box.");
			daysCombo.setEnabled(false);
			//cl.show(cards, Constants.GRID_PANEL);
			
		}

	}

	public void propertyChange(PropertyChangeEvent evt) {
		if ("progress" == evt.getPropertyName()) {
			int progress = (Integer) evt.getNewValue();
			pbar.setValue(progress);
			// plan.notify();
			// taskOutput.append(String.format("Completed %d%% of task.\n", task
			// .getProgress()));
		}
	}

	@Override
	public void mouseClicked(MouseEvent me) {
		// TODO Auto-generated method stub
		int Key = me.getModifiers();  
        
        Component comp = me.getComponent();  
        
       if(comp.getName().equals("starchi")) {
       	JOptionPane
			.showMessageDialog(
					new JFrame(),
					"Diseno e implementacion\n" +
					"Luis Carlos Guerrero Covo\n",
					"Acerca de Planeamiento Produccion GERCO",
					JOptionPane.INFORMATION_MESSAGE,starryicon);
       }
		
	}

	@Override
	public void mouseEntered(MouseEvent me) {
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent me) {
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	public boolean getActualizarStatus() {
		return changestatus;
	}
	
	public void resetActualizarStatus() {
		if(mostrarButton!=null) {
			mostrarButton.setEnabled(true);
		}
		if(monthsCombo!=null) {
			monthsCombo.setEnabled(true);
		}
		if(yearCombo!=null) {
			yearCombo.setEnabled(true);
		}
		if(daysCombo!=null) {
			daysCombo.setEnabled(true);
		}
		changestatus = false;
	}
	
	public void updateStatus() {
		daysCombo.setEnabled(false);
		glassPanel.setVisible(true);
		
		if(jsp!=null) {
			jsp.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
			jsp.setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_NEVER);

		}
		buttonPanel.setEnabled(false);
		
		daysCombo.removeActionListener(this);
		daysCombo.setSelectedIndex(0);
		daysCombo.addActionListener(this);
		if(monthsCombo!=null) {
			monthsCombo.setEnabled(false);
		}
		if(yearCombo!=null) {
			yearCombo.setEnabled(false);
		}
		if(daysCombo!=null) {
			daysCombo.setEnabled(false);
		}
		
		if(actualizarButton!=null) {
			actualizarButton.setEnabled(false);
		}
		
		if(pdfButton!=null) {
			pdfButton.setEnabled(false);
		}
	}
	
	public void setYearIndex(int index) {
		yearCombo.removeActionListener(this);
		yearCombo.setSelectedIndex(index);
		yearCombo.addActionListener(this);
	}

	public void setMonthIndex(int index) {
		monthsCombo.removeActionListener(this);
		monthsCombo.setSelectedIndex(index);
		monthsCombo.addActionListener(this);
	}
	
	public void setDayIndex(int index) {
		daysCombo.removeActionListener(this);
		daysCombo.setSelectedIndex(index);
		daysCombo.addActionListener(this);
	}

	

}
